from src.action.base_bot import BaseBot
import re
import json
import time
import random
import jmespath
from DrissionPage._configs.chromium_options import ChromiumOptions
from DrissionPage._pages.chromium_page import ChromiumPage
from loguru import logger


class YoutubeServer(BaseBot):
    name = "yt"

    def __init__(self):
        super().__init__()
        self.base_url = 'https://www.youtube.com/watch?v={}'

    def get_proxy_v2(self):
        return {"ip": "127.0.0.1", "port": 7890}

    def login_account(self, vid):
        self.page.get(self.base_url.format(vid))
        # cookies = """"""
        # cookies = json.loads(cookies)
        # self.page.set.cookies(cookies)
        # self.page.refresh()
        time.sleep(2)
        if 'aria-label="登录"' not in self.page.html:
            return True
        else:
            return False

    def check_post_comment(self, submit_button, reply_type):
        comment_id = ''
        if reply_type == 'reply_post':
            self.page.listen.start('https://www.youtube.com/youtubei/v1/comment/create_comment?prettyPrint=false')
            time.sleep(random.uniform(0.5, 2.0))
            submit_button.click()
            res = self.page.listen.wait(timeout=10)
            if res:
                data_json = res.response.body
                comment_id = jmespath.search(
                    'actions[1].createCommentAction.contents.commentThreadRenderer.commentViewModel.commentViewModel.commentId',
                    data_json)
        else:
            self.page.listen.start('https://www.youtube.com/youtubei/v1/comment/create_comment_reply?prettyPrint=false')
            time.sleep(random.uniform(0.5, 2.0))
            submit_button.click()
            res = self.page.listen.wait(timeout=10)
            if res:
                data_json = res.response.body
                comment_id = jmespath.search('actions[1].createCommentReplyAction.contents.commentViewModel.commentId',
                                             data_json)
        self.page.listen.stop()
        return comment_id

    def match_vid(self, post_url):
        vid = re.findall(r'v=(.*)', post_url) or re.findall(r'v=(.*)\?', post_url) or \
              re.findall(r'shorts/(.*)', post_url) or re.findall(r'shorts/(.*)\?', post_url) or \
              re.findall(r'/live/(.*)', post_url) or re.findall(r'/live/(.*)\?', post_url)
        if vid:
            return vid[0]

    def load_all_comments(self):
        """
        持续向下滚动页面，直到所有评论都加载完毕。
        """
        self.page.listen.start('https://www.youtube.com/youtubei/v1/next?prettyPrint=false')
        last_height = self.page.run_js('return document.documentElement.scrollHeight')
        while True:
            self.page.scroll.to_bottom()
            try:
                self.page.listen.wait(timeout=5)
                print("监听到新的评论数据加载。")
            except TimeoutError:
                print("未监听到新的评论加载请求，可能已到底部。")
            time.sleep(1)
            new_height = self.page.run_js('return document.documentElement.scrollHeight')
            if new_height == last_height:
                print("页面高度未变，确认所有评论已加载完毕。")
                break
            last_height = new_height
        self.page.listen.stop()

    def load_page(self):
        try:
            co = ChromiumOptions()
            co.set_user_data_path(r'D:\Chrome_user_data\User Data')
            # co.incognito()  # 无痕模式
            # co.headless()  # 无头模式
            # user_data_dir = 'C:/Users/sky/AppData/Local/Google/Chrome/User Data'
            # co.set_argument('--no-sandbox')  # 无沙盒模式
            # co.set_argument('--headless', 'new')
            # co.set_argument('browser_path', '/usr/bin/google-chrome')
            # co.set_user_data_path(user_data_dir)  # 隔离用户数据
            # co.set_argument('--window-size', '1000,600')
            # co.headless = False
            proxy_dict = self.get_proxy_v2()
            if proxy_dict:
                proxy = f"http://{proxy_dict['ip']}:{proxy_dict['port']}"
                logger.info(f"设置代理: {proxy}")
                co.set_proxy(proxy)
            login_page = ChromiumPage(addr_or_opts=co)
            ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0"
            login_page.set.user_agent(ua)
            self.page = login_page
        except Exception as e:
            print(f"创建登录页面失败: {str(e)}")
            return None

    def random_chose_account(self):
        pass

    def comment_post(self, post_url, comment_content):
        if post_url:
            vid = self.match_vid(post_url)
            if vid:
                try:
                    res = self.login_account(vid)
                    if res:
                        if vid in self.page.html:
                            self.page.listen.start('https://www.youtube.com/youtubei/v1/next?prettyPrint=false')
                            self.page.scroll.to_bottom()
                            self.page.listen.wait()  # 等待评论加载
                            cmt_tab = self.page.ele('xpath://div[@id="simple-box"]//div[@id="placeholder-area"]')
                            cmt_tab.click()
                            cmt_tab.input(comment_content)
                            submit_button = self.page.ele(
                                'xpath://div[@id="comment-dialog"]//div[@id="thumbnail-input-row"]//ytd-button-renderer[@id="submit-button"]')
                            comment_id = self.check_post_comment(submit_button, 'reply_post')
                            return {'code': 200, "msg": f"{post_url} 帖子成功", 'data': {"comment_id": comment_id}}
                        else:
                            return {'code': 500, "msg": f"{post_url} 帖子不存在或者页面加载不成"}
                    else:
                        return {'code': 500, "msg": f"登录失败，请重试"}
                except Exception as e:
                    return {'code': 500, "msg": f"{post_url} 评论失败，{e}"}
            else:
                return {'code': 500, "msg": f"{post_url} url格式错误"}
        else:
            return {'code': 500, "msg": "没有post_url"}

    def comment_comment(self, url, comment_content, by_comment_content):
        if url:
            vid = self.match_vid(url)
            if vid:
                try:
                    res = self.login_account(vid)
                    if res:
                        if vid in self.page.html:
                            self.load_all_comments()
                            comment_items = self.page.eles('xpath://div[@id="contents"]/ytd-comment-thread-renderer')
                            for comment_item in comment_items:
                                comment_text = comment_item.ele(
                                    'xpath://yt-attributed-string[@id="content-text"]//text()')
                                if comment_text.lower() == by_comment_content.lower():
                                    comment_item.ele('xpath://ytd-button-renderer[@id="reply-button-end"]').click()
                                    cmt_tab = comment_item.ele(
                                        'xpath://div[@id="reply-dialog"]//tp-yt-paper-input-container')
                                    cmt_tab.input(comment_content)
                                    submit_button = comment_item.ele(
                                        'xpath://div[@id="reply-dialog"]//ytd-button-renderer[@id="submit-button"]')
                                    comment_id = self.check_post_comment(submit_button, 'reply_comment')
                                    return {'code': 200, "msg": f"{url} 帖子成功",
                                            'data': {"comment_id": comment_id}}
                        else:
                            return {'code': 500, "msg": f"{url} 帖子不存在或者页面加载不成"}
                    else:
                        return {'code': 500, "msg": f"登录失败，请重试"}
                except Exception as e:
                    return {'code': 500, "msg": f"{url} 评论失败，{e}"}
            else:
                return {'code': 500, "msg": f"{url} url格式错误"}
        else:
            return {'code': 500, "msg": "没有post_url"}


if __name__ == '__main__':
    # ytb = YoutubeServer()
    # try:
    #     ytb.load_page()
    #     res = ytb.comment_post('https://www.youtube.com/shorts/Rjq2nWevtN4', '一段')
    #     # res = ytb.comment_comment('https://www.youtube.com/shorts/Rjq2nWevtN4', '下午好', '南北路多')
    #     print(res)
    # except:
    #     pass
    # finally:
    #     ytb.page.close()
    YoutubeServer().start_action()
